package com.kangjia.model.service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kangjia.type.Md5;
import com.kangjia.util.VerifyCodeUtils;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
@Slf4j
public class CookieService {

	public String ROOT_PATH = "/";

	public String CK_NAME = "KJHW";
	
	@Autowired
	protected JedisPool jedisPool;
	
	public String encrypt(String ip) {
		String verifyCode = VerifyCodeUtils.generateVerifyCode(6);
		String encrypt = Md5.encrypt(ip + verifyCode);
		log.info("客户端ip={}, 随机码={}", ip, verifyCode);
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.set(encrypt, "");
			jedis.expire(encrypt, 3600);
		} finally {
			jedis.close();
		}
		return encrypt;
	}

	public Cookie read(HttpServletRequest request) {
		Cookie ret = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CK_NAME)) {
					ret = cookie;
					break;
				}
			}
		}
		return ret;
	}

	public Cookie write(HttpServletResponse response, String domain, String value) {
		Cookie cookie = new Cookie(CK_NAME, value);
		cookie.setDomain(domain);
		cookie.setHttpOnly(true);
		cookie.setPath(ROOT_PATH);
		cookie.setMaxAge(3600);
		response.addCookie(cookie);
		return cookie;
	}
}
